const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const messageManage = require('./messageManage');
const flowService = require('./flowService');
const deviceService = require('./deviceService');

const app = new Koa();
const port = process.env.HTTP_PORT || 3000;



const router = new Router();

app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

app.use(bodyParser());

app.use(router.routes());

router.post('/device', async (ctx, next) => {
    const data = ctx.request.body;
    const device = deviceService.create(data);
    const deviceId = device.id;
    flowService.start(flowId);
    ctx.body = '增加了一个流程';
});

router.post('/flow', async (ctx, next) => {
    const data = ctx.request.body;
    const flow = flowService.create(data);
    const flowId = flow.uuid;
    flowService.start(flowId);
    ctx.body = '增加了一个流程';
});

//
router.get('/message/list/:deviceId', async (ctx, next) => {
    ctx.type = 'json';
    const params = ctx.params;
    const deviceId = params.deviceId;
    const messageList = messageManage.getList(deviceId);
    ctx.body = messageList;
    console.log(messageList);
});

app.listen(3000);

console.log(`启动Http服务，端口：${port}`);